using MauiBuilder.Services;
using MauiBuilder.ViewModels;
using Microsoft.Maui.Controls.Shapes;

namespace MauiBuilder.Views;

public partial class HybridWebPage : ContentPage
{
    private readonly HybridWebViewModel _viewModel;

    public HybridWebPage(HybridWebViewModel viewModel)
    {
        InitializeComponent();
        BindingContext = _viewModel = viewModel;
        InitializeWebView();
    }

    /// <summary>
    /// 初始化HybridWebView
    /// </summary>
    private void InitializeWebView()
    {
        // 设置HybridWebView引用到ViewModel
        _viewModel.SetHybridWebView(hyWebView);
    }

    /// <summary>
    /// HybridWebView原始消息接收事件
    /// </summary>
    private void OnHybridWebViewRawMessageReceived(object? sender, HybridWebViewRawMessageReceivedEventArgs e)
    {
        try
        {
            _viewModel.HandleJavaScriptMessage(e.Message ?? "");
        }
        catch (Exception ex)
        {
            LogManager.Instance.LogError($"Error handling HybridWebView message: {ex.Message}", ex);
        }
    }

    /// <summary>
    /// 页面出现时
    /// </summary>
    protected override void OnAppearing()
    {
        base.OnAppearing();

        // 可以在这里添加页面出现时的逻辑
    }

    /// <summary>
    /// 页面消失时
    /// </summary>
    protected override void OnDisappearing()
    {
        base.OnDisappearing();
        _viewModel?.OnDisappearing();
    }
}